# !/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.cache import cache

import info.models
from activativies.utils import send_msg
from teacher.models import Teacher, Trelation

try:
    from django.utils.deprecation import MiddlewareMixin  # Django 1.10.x
except ImportError:
    MiddlewareMixin = object  # Django 1.4.x - Django 1.9.x


class SimpleMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if request.method == 'POST':
            if request.path == '/admin/activativies/activity/add/':
                # 拦截到添加活动
                act_name = f'新任务：{request.POST["name"]}'
                # 查询所有登记了wx_group的班群
                cla = info.models.Class.objects.all()
                for c in cla:
                    if c.wx_group:
                        # 如果班群不为空
                        send_msg(
                            # msg_type=data['type'],
                            msg_type=100,
                            msg=act_name,
                            to_wxid=c.wx_group,
                            # at_wxid=data['final_from_wxid'],
                            # at_name=data['from_name']
                        )
                    print(act_name)

            if request.path == '/admin/teacher/trelation/add/' or request.path == '/admin/teacher/trelation/89/change/':
                teacher_id = request.POST['teacher']
                teacher = Teacher.objects.get(id=teacher_id)
                cache.set(
                    f'teacher:{teacher.teacher_card}',
                    [
                        {
                            'id': i.id,
                            'name': i.name
                        } for i in Trelation.objects.filter(teacher_id=teacher.id)
                    ],
                    None
                )
                print(teacher)

            if '/admin/leave/leavelog' in request.path:
                # 标记请假审核人
                data = request.POST.copy()
                name = request.user.last_name + request.user.first_name
                # data['operator'] = name
                for i in range(int(request.POST['form-TOTAL_FORMS'])):
                    data[f'form-{i}-operator'] = name

                request.POST = data
                print(name)
